package com.yanqu.road.server.manger.activity.seacraft;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.seacraft.config.SeacraftSouthSeaActivityConfig;
import com.yanqu.road.entity.player.UserInfo;
import com.yanqu.road.entity.player.UserPatrons;
import com.yanqu.road.entity.union.UnionBaseInfo;
import com.yanqu.road.entity.union.UnionInfo;
import com.yanqu.road.logic.helper.ActivityHelper;
import com.yanqu.road.logic.pb.UnionBasePb;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.pb.activity.SeacraftSouthSeaProto;
import com.yanqu.road.pb.union.UnionProto;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.patrons.PatronsModule;
import com.yanqu.road.server.manger.SeacraftSouthSeaCommonMgr;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.player.UserMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.utils.YanQuMessageUtils;
import com.yanqu.road.utils.date.DateHelper;
import com.yanqu.road.utils.string.StringUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class SeacraftSouthSeaActivity {
    private int groupId;
    private int activityId;
    /**
     * 每个轮次晋级名单 k:轮次 v:晋级联盟id
     */
    private Map<Integer, List<String>> roundJoinUnionMap = new ConcurrentHashMap<>();

    // 需要上传玩家派遣对象 k:userId k:系统id v 对象集合
    private ConcurrentHashMap<Long, Set<Integer>> needUploadObjectInfoMap = new ConcurrentHashMap<>();

    public SeacraftSouthSeaActivity(int groupId, int activityId) {
        this.groupId = groupId;
        this.activityId = activityId;
    }

    public int getGroupId() {
        return groupId;
    }

    public int getActivityId() {
        return activityId;
    }

    public Map<Integer, List<String>> getRoundJoinUnionMap() {
        return roundJoinUnionMap;
    }

    public void setRoundJoinUnionMap(Map<Integer, List<String>> roundJoinUnionMap) {
        this.roundJoinUnionMap = roundJoinUnionMap;
    }

    public ConcurrentHashMap<Long, Set<Integer>> getNeedUploadObjectInfoMap() {
        return needUploadObjectInfoMap;
    }

    public void setNeedUploadObjectInfoMap(ConcurrentHashMap<Long, Set<Integer>> needUploadObjectInfoMap) {
        this.needUploadObjectInfoMap = needUploadObjectInfoMap;
    }

    /**
     * 是否晋级
     *
     * @return
     */
    public boolean isPromotion(String unionId) {
        if (StringUtils.isNullOrEmpty(unionId)) {
            return false;
        }
        int curRound = SeacraftSouthSeaCommonMgr.getCurRound(SeacraftSouthSeaMgr.getActivityInfo(), SeacraftSouthSeaMgr.getConfig());
        List<String> unionList = roundJoinUnionMap.get(curRound);
        if (unionList == null) {
            return false;
        }
        for (String item : unionList) {
            if (item.equals(unionId)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 向跨服索要晋级联盟的数据
     */
    public synchronized void getPromotionUnionList(ActivityInfo activityInfo, SeacraftSouthSeaActivityConfig config) {
        int round = SeacraftSouthSeaCommonMgr.getCurRound(activityInfo, config);
        if (round <= 0 || config.roundTimeList.size() < round) {
            if (roundJoinUnionMap.size() != 0) {
                roundJoinUnionMap.clear();
            }
            return;
        }
        if (roundJoinUnionMap.size() < round) {
            SeacraftSouthSeaProto.SeacraftSouthSeaGetPromotionUnionGameToCrossMsg.Builder builder = SeacraftSouthSeaProto.SeacraftSouthSeaGetPromotionUnionGameToCrossMsg.newBuilder();
            builder.setActivityId(activityInfo.getActivityId());
            GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C2_SEACRAFT_SOUTH_SEA_GET_PROMOTION_UNION, builder, 0, activityInfo.getActivityId(), groupId);
        }
    }

    public void synPatronsAbility(GamePlayer player, List<UserPatrons> patronsList) {
        if (patronsList == null) {
            return;
        }
        if (StringUtils.isNullOrEmpty(player.getUserInfo().getUnionUid())) {
            return;
        }
        // 判断该玩家的联盟是否晋级
        int curRound = SeacraftSouthSeaCommonMgr.getCurRound(SeacraftSouthSeaMgr.getActivityInfo(), SeacraftSouthSeaMgr.getConfig());
        if (curRound > SeacraftSouthSeaMgr.getConfig().roundTimeList.size()) {
            // 最后一轮了 判断是否结束了
            return;
        }
        // 本轮晋级的联盟id
        List<String> unionList = roundJoinUnionMap.get(curRound);
        if (unionList == null || !unionList.contains(player.getUserInfo().getUnionUid())) {
            return;
        }
        synchronized (needUploadObjectInfoMap) {
            Set<Integer> set = needUploadObjectInfoMap.get(player.getUserId());
            if (set == null) {
                set = new HashSet();
                needUploadObjectInfoMap.put(player.getUserId(), set);
            }
            for (UserPatrons patrons : patronsList) {
                set.add(patrons.getPatronsId());
            }
        }
    }

    /**
     * 同步门客数据
     */
    public void uploadObjectInfo() {
        synchronized (needUploadObjectInfoMap) {
            if (needUploadObjectInfoMap.size() <= 0) {
                return;
            }
            SeacraftSouthSeaProto.SeacraftSouthSeaSynUserInfoGameToCrossMsg.Builder synUserMsg = SeacraftSouthSeaProto.SeacraftSouthSeaSynUserInfoGameToCrossMsg.newBuilder();
            synUserMsg.setActivityId(SeacraftSouthSeaMgr.getActivityInfo().getActivityId());
            for (Map.Entry<Long, Set<Integer>> entry : needUploadObjectInfoMap.entrySet()) {
                long userId = entry.getKey();
                GamePlayer player = GamePlayerMgr.getOnlinePlayer(userId);
                if (player == null) {
                    continue;
                }
                SeacraftSouthSeaProto.SeacraftSouthSeaSynUserPatronsInfo.Builder userPatronsInfo = SeacraftSouthSeaProto.SeacraftSouthSeaSynUserPatronsInfo.newBuilder();
                userPatronsInfo.setUserId(player.getUserId());
                for (Integer patronsId : entry.getValue()) {
                    PatronsModule patronsModule = player.getModule(PatronsModule.class);
                    UserPatrons userPatrons = patronsModule.getUserPatrons(patronsId);
                    if (userPatrons != null) {
                        userPatronsInfo.addPatronsList(SeacraftSouthSeaMgr.builderSeacraftSouthSeaPatronsEntity(userPatrons));
                    }
                }
                synUserMsg.addUserPatronsList(userPatronsInfo);

            }
            if (synUserMsg.getUserPatronsListCount() > 0) {
                GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C2_SEACRAFT_SOUTH_SEA_SYN_PATRONS_INFO, synUserMsg, 0, activityId, groupId);
            }
            needUploadObjectInfoMap.clear();
        }
    }

    /**
     * 当前阶段是否能进出商会 或解散商会
     *
     * @param unionId
     * @return
     */
    public boolean canInAndOutUnion(String unionId) {
        int curRound = SeacraftSouthSeaCommonMgr.getCurRound(SeacraftSouthSeaMgr.getActivityInfo(), SeacraftSouthSeaMgr.getConfig());
        if (curRound == 0 || curRound > SeacraftSouthSeaMgr.getConfig().roundTimeList.size()) {
            // 不在 海盗之乱结束- 南海丝路结束 区间
            return true;
        }
        if (roundJoinUnionMap.size() != curRound) {
            // 还未同步晋级名单 不让退
            return false;
        }
        // 判断是否有晋级资格 判断当前回合是否有晋级资格，没有没数据 有可能还没同步下来 取上一个回合的
        List<String> unionList = roundJoinUnionMap.get(curRound);
        if (unionList == null) {
            return false;
        }
        return !unionList.contains(unionId);
    }

    /**
     * 获取本轮晋级的联盟集合
     *
     * @return
     */
    public List<String> getCurRoundPromotionUnionList() {
        int curRound = SeacraftSouthSeaCommonMgr.getCurRound(SeacraftSouthSeaMgr.getActivityInfo(), SeacraftSouthSeaMgr.getConfig());
        if (curRound == 0 || curRound > SeacraftSouthSeaMgr.getConfig().roundTimeList.size()) {
            // 不在 海盗之乱结束- 南海丝路结束 区间
            return null;
        }
        // 判断是否有晋级资格 判断当前回合是否有晋级资格，没有没数据 有可能还没同步下来 取上一个回合的
        List<String> unionList = roundJoinUnionMap.get(curRound);
        if (unionList != null) {
            return unionList;
        } else {
            int preRound = curRound - 1;
            if (preRound != 0) {
                return roundJoinUnionMap.get(preRound);
            }
        }
        return null;
    }

    /**
     * 同步联盟信息
     *
     * @param type
     * @param unionId
     * @param userId
     * @param unionInfo
     */
    public void synUnionInfo(ActivityInfo activityInfo, SeacraftSouthSeaActivityConfig config, int type, String unionId, long userId, UnionInfo unionInfo) {
        try {
            if (type == 1) {
                // 联盟信息改变
                int curRound = SeacraftSouthSeaCommonMgr.getCurRound(SeacraftSouthSeaMgr.getActivityInfo(), SeacraftSouthSeaMgr.getConfig());
                if (curRound == 0 || curRound > SeacraftSouthSeaMgr.getConfig().roundTimeList.size()) {
                    // 不在 海盗之乱结束- 南海丝路结束 区间
                    return;
                }
                // 海盗之乱晋级名单
                List<String> joinListRound1 = roundJoinUnionMap.get(1);
                if (joinListRound1 == null || !joinListRound1.contains(unionId)) {
                    return;
                }
                SeacraftSouthSeaProto.SeacraftSouthSeaSynUnionMemberGameToCrossMsg.Builder synUnionMemberGameToCrossMsg = SeacraftSouthSeaProto.SeacraftSouthSeaSynUnionMemberGameToCrossMsg.newBuilder();
                synUnionMemberGameToCrossMsg.setActivityId(SeacraftSouthSeaMgr.getActivityInfo().getActivityId());
                synUnionMemberGameToCrossMsg.setType(1);
                synUnionMemberGameToCrossMsg.setUnionId(unionId);
                UnionBaseInfo unionBaseInfo = CrossUnionMgr.parseUnionBaseInfo(unionInfo.getUnionUid());
                UserInfo userInfo = UserMgr.getUserInfo(unionInfo.getMasterUserId());
                if (userInfo != null) {
                    unionBaseInfo.setHideVipAndAddress(userInfo.getHideVipAndAddress());
                    unionBaseInfo.setSex(userInfo.getSex());
                    unionBaseInfo.setMasterVipExp(userInfo.getVipExp());
                }

                UnionProto.UnionBaseTempMsg.Builder unionMsg = UnionBasePb.parseUnionBaseTempMsg(unionBaseInfo);
                synUnionMemberGameToCrossMsg.setUnionInfo(unionMsg);
                GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C2_SEACRAFT_SOUTH_SEA_SYN_UNION_MEMBER_CHANGE, synUnionMemberGameToCrossMsg, 0, activityId, groupId);
            } else if (type == 2 || type == 3) {
                // 活动开始到 备战期结束都需要同步
                if (!ActivityHelper.activityInTime(activityInfo)) {
                    return;
                }
                int now = DateHelper.getCurrentSecond();
                if (activityInfo.getBeginTime() <= now && now < activityInfo.getBeginTime() + config.pretimeList.get(1)) {
                    // 第一轮活动开始之前
                    SeacraftSouthSeaProto.SeacraftSouthSeaSynUnionMemberGameToCrossMsg.Builder synUnionMemberGameToCrossMsg = SeacraftSouthSeaProto.SeacraftSouthSeaSynUnionMemberGameToCrossMsg.newBuilder();
                    synUnionMemberGameToCrossMsg.setActivityId(SeacraftSouthSeaMgr.getActivityInfo().getActivityId());
                    synUnionMemberGameToCrossMsg.setType(type);
                    synUnionMemberGameToCrossMsg.setUserId(userId);
                    synUnionMemberGameToCrossMsg.setUnionId(unionId);
                    GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C2_SEACRAFT_SOUTH_SEA_SYN_UNION_MEMBER_CHANGE, synUnionMemberGameToCrossMsg, 0, activityId, groupId);
                }
            }
        } catch (Exception e) {
            SeacraftSouthSeaMgr.getLogger().error("同步海上争霸 联盟数据 error", e);
        }
    }
}
